import type { AnyIotSimDetail } from './typings.d';

export const getFlowPercent = (used: string, total: string): string => {
  if (!used || !total) return '0';
  const useUnit = used.slice(-2);
  const totalUnit = total.slice(-2);
  const useValue = parseInt(used);
  const totalValue = parseInt(total);
  if (useValue === 0) return '0';
  if (useUnit === totalUnit) return ((useValue / totalValue) * 100).toFixed(2);
  let tranferUse = useValue;
  let tranferTotal = totalValue;
  if (useUnit == 'GB') {
    tranferUse *= 1024 * 1024;
  } else if (useUnit == 'MB') {
    tranferUse *= 1024;
  }
  if (totalUnit == 'GB') {
    tranferTotal *= 1024 * 1024;
  } else if (totalUnit == 'MB') {
    tranferTotal *= 1024;
  }
  return ((tranferUse / tranferTotal) * 100).toFixed(2);
};

const CTCC_ICCID_PREFIX = ['898603', '898611'];

const CUCC_ICCID_PREFIX = ['898601', '898606', '898609'];

const CMCC_ICCID_PREFIX = ['898600', '898602', '898604', '898607'];
/**
 * 根据卡号查询运营商
 * @param iccid 卡号
 */
function getOperatorByIccid(iccid: string): string {
  if (!iccid) return '';
  const ICCID_PREFIX = CTCC_ICCID_PREFIX.concat(CUCC_ICCID_PREFIX, CMCC_ICCID_PREFIX);
  const index = ICCID_PREFIX.indexOf(iccid.trim().slice(0, 6));
  if (index > 4) return 'CMCC';
  if (index > 1) return 'CTCC';
  if (index >= 0) return 'CUCC';
  return 'UNKNOW';
}

export const parseUpiotPkgName = (val: string) => {
  const reg = /GW\d{3,}G/g;
  let unit = '';
  if (val.endsWith('21')) unit = '月';
  else if (val.endsWith('1211')) unit = '年';
  if (!unit) return val;
  const matchRes = val.match(reg);
  if (!matchRes) return val;
  const size = parseInt(matchRes[0]?.slice(2));
  if (!size) return val;
  return `公网${size}G/${unit}`;
};
// 运营商映射
const mapSupplierToCode = new Map()
  .set('中国移动', 'CMCC')
  .set('中国电信', 'CTCC')
  .set('中国联通', 'CUCC')
  .set('1', 'CMCC')
  .set('2', 'CUCC')
  .set('3', 'CTCC');

const mapCodeToSupplier = new Map()
  .set('CMCC', '中国移动')
  .set('CTCC', '中国电信')
  .set('CUCC', '中国联通');

export const handleSupplier = (rawData: AnyIotSimDetail) => {
  const { provider, info } = rawData;
  if (provider == 'tibiot') {
    const tp = mapSupplierToCode.get(info.operator);
    return mapCodeToSupplier.get(tp);
  } else if (provider == 'upiot') {
    const tp = mapSupplierToCode.get(info.carrier);
    return mapCodeToSupplier.get(tp);
  } else if (provider == 'dahan') {
    const { flowPackage } = info;
    if (flowPackage?.length < 1) {
      return getOperatorByIccid(info.iccid);
    }
    const { pkgCode, pkgName } = flowPackage[0];
    const tp =
      pkgCode?.split('_')[0]?.toUpperCase() ||
      mapSupplierToCode.get(pkgName?.slice(0, 4)) ||
      getOperatorByIccid(info.iccid);
    return mapCodeToSupplier.get(tp);
  }
  return '未知运营商';
};
